<?php

namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use util\Date;
use util\File;
use function Symfony\Component\String\u;

class WxUser extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;
    protected $role;

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($authorization)) {
            responseJson(-100, '请先登录');
        }
        $this->openid = $authorization;
        $user = Db::name('member')->where('openid', '=', $this->openid)
            ->field('id,money,level_id,coupon1,coupon2,openid,nickname,avatarUrl,mobile,status,fraction,code_url,invite_id,min_tx,is_clock')->find();
        if (empty($user)) {
            responseJson(-100, '登录信息有误');
        }
        if ($user['status'] == 0) {
            msg(-200, '用户已冻结', $user);
        }
        if (!strpos($user['avatarUrl'], 'ttp')) {
            $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
        }
        $this->memberInfo = $user;
        $this->memberId = $user['id'];
    }

    /**
     * 获取用户信息
     */
    public function getMemberInfo()
    {
        //会员二维码
        if (!$this->memberInfo['code_url']) {
            $code_url = qrcode($this->memberId, '');
            Db::name('member')->update([
                'id' => $this->memberId,
                'code_url' => $code_url
            ]);
        }
        $level_info = Db::name('member_level')->find($this->memberInfo['level_id']);
        $this->memberInfo['level_info'] = $level_info;
        msg(0, '查询成功', $this->memberInfo);
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 修改用户信息
     */
    public function updateUserinfo()
    {
        $data = $this->request->param();
        $update_data = array();
        if (isset($data['mobile']) && $data['mobile']) {
            $update_data['mobile'] = $data['mobile'];
        }
        if (isset($data['nickname']) && $data['nickname']) {
            $update_data['nickname'] = $data['nickname'];
        }
        if (isset($data['avatarUrl']) && $data['avatarUrl']) {
            $update_data['avatarUrl'] = $data['avatarUrl'];
        }
        $stmt = Db::name('member')
            ->where('openid', $this->openid)
            ->update($update_data);
        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(-1, "修改失败", []);
        }
    }

    //获取地址列表
    public function getAddressList()
    {
        $member_id = $this->memberInfo['id'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $member_id];
        $data = Db::name('member_address')
            ->where($where)
            ->order('is_default_address desc')
            ->order('create_time desc')
            ->select();
        msg(0, "查询成功", $data);
    }

    //增加收货地址
    public function addAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'member_id' => $this->memberInfo['id'],
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $insert_id = Db::name('member_address')->insertGetId($save_data);
            Db::commit();
            msg(0, '添加成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //设置默认地址
    public function setDefaultAddress()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            Db::name('member_address')
                ->where(['member_id' => $this->memberId])
                ->update(['is_default_address' => 0]);
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update([
                    'is_default_address' => 1
                ]);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //编辑收货地址
    public function editAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update($save_data);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取默认地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getDefaultAddress()
    {
        $data = $this->getAddress();
        msg(0, '查询成功', $data);
    }

    public function getAddress()
    {
        $where[] = ['is_default_address', '=', 1];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberInfo['id']];
        $data = Db::name('member_address')->where($where)->find();
        return $data;
    }

    /**
     * 通过id获取地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getAddress2()
    {
        $data = $this->request->param();
        $addressData = $this->getAddressById($data['id']);
        msg(0, '查询成功', $addressData);
    }

    public function getAddressById($id)
    {
        return Db::name('member_address')->find($id);
    }

    //删除地址
    public function delAddress()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['address_id'],
            'is_del' => 1
        );
        $order_data = Db::name('member_address')->update($update);
        msg(0, "删除成功", $order_data);
    }

    /**
     * 加入购物车
     */
    public function addGoodsCar()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['attr_name']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                ->where($where)
                ->find();
//            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $is_on_car = Db::name('goods_car')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id'],
                'attr_name' => $data['attr_name']
            ])->find();
            if ($is_on_car) {
                Db::name('goods_car')->where([
                    'member_id' => $this->memberId,
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name']
                ])->setInc('num', $data['num']);
            } else {
                $insert_data = array(
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name'],
                    'member_id' => $this->memberId,
                    'num' => $data['num'],
                    'create_time' => time(),
                );
                Db::name('goods_car')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取购物车列表
    public function getGoodsCarList()
    {
        $data_list = Db::name('goods_car')
            ->alias('gc')->join('goods g', 'gc.goods_id=g.id')
            ->field('gc.*,g.name as goods_name,g.first_img,g.desc,g.is_del as goods_is_del')
            ->where(['member_id' => $this->memberId])
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $is_buy = 1;
            $goods_attr_value = Db::name('goods_attr_value')->where([
                'goods_id' => $v['goods_id'],
                'suk' => $v['attr_name']
            ])->order('id')->find();
            if (!$goods_attr_value || $v['goods_is_del']) {
                $is_buy = 0;
            }
            $data_list[$k]['goods_attr_value'] = $goods_attr_value;
            $data_list[$k]['is_buy'] = $is_buy;
            $data_list[$k]['sumPrice'] = round($data_list[$k]['num'] * $goods_attr_value['price'], 2);
        }
        msg(0, '添加完成', $data_list);
    }

    //删除购物车商品
    public function delGoodsCarList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where('id', 'in', $data['goods_car_ids'])
            ->delete();
        msg(0, '删除完成', '');
    }

    //修改购物车商品数量
    public function updateGoodsCardList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where(['id' => $data['goods_car_id']])
            ->update(['num' => $data['num']]);
        msg(0, '修改完成', '');
    }

    //视频列表
    public function videoList2()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $data_list = Db::name('video')->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['isKan'] = $this->isKan($item['id']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    public function isKan($video_id)
    {
        $info = Db::name('member_video')
            ->where([
                'member_id' => $this->memberId,
                'video_id' => $video_id
            ])
            ->find();
        if ($info) {
            return 1;
        }
        return 0;
    }

    //视频详情
    public function videoDetail()
    {
        $data = $this->request->param();
        $video = Db::name('video')->find($data['id']);
        msg(0, '修改完成', $video);
    }

    //看完视频调用
    public function seeFinishVideo()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $is_kan = $this->isKan($data['id']);
            if (!$is_kan) {
                $video = Db::name('video')->find($data['id']);
                $insert_data = array(
                    'member_id' => $this->memberId,
                    'video_id' => $data['id'],
                    'points' => $video['points'],
                    'create_time' => time()
                );
                Db::name('member_video')->insertGetId($insert_data);
                addFraction($this->memberId, $video['points'], '用户看视频');
            }
//            else{
//                msg(-1, '视频已观看', '');
//            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //商城兑换
    //积分兑换 todo 测试修改
    public function fractionExchange()
    {
        $data = $this->request->param();
        $goods_info = Db::name('points_goods')->where(['id' => $data['id']])->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        Db::startTrans();
        try {
            if ($goods_info['points'] > $this->memberInfo['coupon1']) {
                msg(-1, '购物卷不足', '');
            }
            $insert_goods_order_data = array(
                'no' => GetOrderSN(2),
                'goods_id' => $data['id'],
                'member_id' => $this->memberId,
                'create_time' => time(),
                'points' => $goods_info['points'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['img']
            );
            $insert_goods_order_data['is_express'] = 1;
            $insert_goods_order_data['realname'] = $data['people'];
            $insert_goods_order_data['telphone'] = $data['phone'];
            $insert_goods_order_data['province'] = $data['province'];
            $insert_goods_order_data['city'] = $data['city'];
            $insert_goods_order_data['area'] = $data['area'];
            $insert_goods_order_data['address'] = $data['address'];
            $goods_order_id = Db::name('points_goods_order')->insertGetId($insert_goods_order_data);
            //兑换数量
            Db::name('points_goods')->where('id', '=', $data['id'])->setInc('sale_num');
            addGWCoupons($this->memberId, -$goods_info['points'], '', $goods_order_id, 5, '购物券兑换');
            Db::commit();
            msg(0, '兑换成功', $goods_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function fractionExchange2()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')->find($data['goods_id']);
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        if ($goods_info['goods_area'] != 5) {
            msg(-1, '非兑换区商品', '');
        }
        Db::startTrans();
        try {
            if ($goods_info['points'] > $this->memberInfo['coupon1']) {
                msg(-1, '购物卷不足', '');
            }
            //判断库存 是否可买
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['suk']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                ->where($where)
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在,或下架', '');
            }
            if ($goods_info['stock'] < $data['num']) {
                msg(-1, '商品库存不足', '');
            }
            $insert_data = array(
                'order_no' => GetOrderSN(2),
                'member_id' => $this->memberId,
//                'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
                'points' => $goods_info['points'],
                'pay_status' => 1,
                'create_time' => time(),
                'pay_time' => time(),
                'order_type' => $goods_info['goods_area'], //订单类型 1拼团区 2臻品区 3砍价区 4健康区
                'people' => $data['people'],
                'phone' => $data['phone'],
                'delive_type' => $data['delive_type'],
                'remark' => $data['remark']
            );
            $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
            $insert_data['order_money'] = $insert_data['origin_price'];
            if ($data['delive_type'] == 1) {
                $insert_data['province'] = $data['province'];
                $insert_data['city'] = $data['city'];
                $insert_data['area'] = $data['area'];
                $insert_data['address'] = $data['address'];
                $insert_data['supply_id'] = $goods_info['supply_id'];
                $insert_data['status'] = 2;
            }
            if ($data['delive_type'] == 2) {
                $insert_data['shop_id'] = $data['shop_id'];
                $insert_data['status'] = 8;
            }
            $insert_data['shop_get_money'] = getShopMoney($insert_data);
            $order_id = Db::name('order')->insertGetId($insert_data);
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            //兑换数量
            Db::name('goods')->where('id', '=', $data['id'])->setInc('sale_num');
            addGWCoupons($this->memberId, -$goods_info['points'], '', $order_id, 5, '购物券兑换');
            Db::commit();
            msg(0, '兑换成功', $order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //兑换记录
    public function PGoodsOrderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        if (isset($data['status']) && $data['status']) {
            $where[] = ['status', '=', $data['status']];
        }
        $data_list = Db::name('points_goods_order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //兑换记录最新
    public function PGoodsOrderList2()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['order_type', 'in', [5]];
        $where[] = ['member_id', '=', $this->memberId];
        if ($data['type'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 8]];
        }
        if (isset($data['type']) && $data['type']) {
            if ($data['type'] == 1) {
                $where[] = ['status', 'in', [1]];
            }
            if ($data['type'] == 2) {
                $where[] = ['status', 'in', [8]];
            }
            if ($data['type'] == 3) {
                $where[] = ['status', 'in', [2]];
            }
            if ($data['type'] == 4) {
                $where[] = ['status', 'in', [3]];
            }
            if ($data['type'] == 5) {
                $where[] = ['status', 'in', [4, 5]];
            }
        }
        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time2'] = $item['create_time'];
                $item['dai_zf_time1'] = $item['create_time'] + (60 * 15);
                $item['dai_zf_time'] = date('Y-m-d H:i:s', $item['create_time'] + (60 * 15));
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->select();
                $item['order_goods'] = $order_goods;
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //积分明细
    public function fractionHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //cate 0收入 1支出
        $type = $data['cate'];
        $where[] = ['member_id', '=', $this->memberId];
        if ($type == 1) {
            $where[] = ['num', '>', 0];
        } elseif ($type == 2) {
            $where[] = ['num', '<', 0];
        }
        $data_list = Db::name('member_coupon1')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //购物商城顶部信息
    public function topGwCoupons()
    {
        $return['coupons'] = $this->memberInfo['coupon1'];
//        $return['coupons_msg'] = '150购物券将于06-30过期';
        $return['coupons_msg'] = '本月无过期购物卷';
        msg(0, '查询成功', $return);
    }

    /**
     * 收藏物品
     */
    public function collectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $is_collect = Db::name('collect_goods')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            ])->find();
            if ($is_collect) {
                msg(-2, '商品已收藏', '');
            }
            $insert_data = array(
                'create_time' => time(),
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            );
            Db::name('collect_goods')->insertGetId($insert_data);
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 取消收藏
     */
    public function cancelCollectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')
                ->where(['id' => $data['goods_id']])
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $where = array(
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            );
            Db::name('collect_goods')->where($where)->delete();
            Db::commit();
            msg(0, '取消收藏', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断商品是否收藏
    public function isCollect($goods_id)
    {
        $is_collect = Db::name('collect_goods')->where([
            'goods_id' => $goods_id,
            'member_id' => $this->memberId
        ])->find();
        if ($is_collect) {
            return 1;
        }
        return 0;
    }

    //收藏列表
    public function collectList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $data_list = Db::name('collect_goods')->alias('c')
            ->join('goods g', 'c.goods_id=g.id')
            ->field('c.*,g.name as goods_name,g.first_img')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }

    //获取订单商品可用购物卷金额
    public function getGoodsCoupons1()
    {
        $data = $this->request->param();
        //goods_id suk num
        $coupons = 0;
        $goods_attr_data = Db::name('goods_attr_value')->where([
            'goods_id' => $data['goods_id'],
            'suk' => $data['suk'],
        ])->find();
        if ($goods_attr_data) {
            $coupons = $goods_attr_data['coupons'];
        }
        $use_coupons = $coupons * $data['num'];
        $this->memberInfo['coupon1'] >= $use_coupons ? $return_coupons = $use_coupons : $return_coupons = $this->memberInfo['coupon1'];
        $c = array();
        $c[0]['value'] = $return_coupons;
        $c[0]['is_able'] = 1;
        msg(0, '查询成功', $c);
    }

    //获取商品可用优惠卷
    public function getMemberCoupons()
    {
        $data = $this->request->param();
        $goods_attr_data = Db::name('goods_attr_value')->where([
            'goods_id' => $data['goods_id'],
            'suk' => $data['suk'],
        ])->find();
        if (!$goods_attr_data) {
            msg(-1, '商品不存在', '');
        }
        $sum_price = $goods_attr_data['price'] * $data['num'];
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $where2[] = ['min_amount', '<=', $sum_price];
        $data_list = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            if ($v['min_amount'] <= $sum_price) {
                $data_list[$k]['is_able'] = 1;
            } else {
                $data_list[$k]['is_able'] = 0;
            }
        }
        msg(0, '查询成功', $data_list);
    }


    //判断优惠卷是否能用
    public function getMemberCouponAble()
    {
        $data = $this->request->param();
        $member_coupons_list = Db::name('member_coupons')->where([
            ['member_id', '=', $this->memberId],
            ['min_amount', '<', $data['money']],
        ])->select();
        msg(0, '创建完成', $member_coupons_list);
    }



    //订单列表
    //    0全部订单  1待付款 2待取货 3待发货 4待收货 5已完成
    // status       1待支付 2待发货 3待收货 4已完成       5已评价 6售后退货 7已取消 8待取货
    //
    public function orderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['order_type', 'in', [1, 2, 3, 4]];
        $where[] = ['member_id', '=', $this->memberId];
        if ($data['type'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 8]];
        }
        if (isset($data['type']) && $data['type']) {
            if ($data['type'] == 1) {
                $where[] = ['status', 'in', [1]];
            }
            if ($data['type'] == 2) {
                $where[] = ['status', 'in', [8]];
            }
            if ($data['type'] == 3) {
                $where[] = ['status', 'in', [2]];
            }
            if ($data['type'] == 4) {
                $where[] = ['status', 'in', [3]];
            }
            if ($data['type'] == 5) {
                $where[] = ['status', 'in', [4, 5]];
            }
        }
        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time2'] = $item['create_time'];
                $item['dai_zf_time1'] = $item['create_time'] + (60 * 15);
                $item['dai_zf_time'] = date('Y-m-d H:i:s', $item['create_time'] + (60 * 15));
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->select();
                $item['order_goods'] = $order_goods;
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //取消订单
    public function cancelOrder()
    {
        $data = $this->request->param();
        //修改订单状态
        //修改优惠券
        Db::startTrans();
        try {
            $order_info = Db::name('order')->where('order_no', '=', $data['id'])->find();
            if (!$order_info) {
                msg(-1, '订单不存在', '');
            }
            if ($order_info['status'] != 1) {
                msg(-1, '订单状态不是待支付', '');
            }
            $order_data = array(
                'id' => $data['id'],
                'status' => 7,
            );
            Db::name('order')->update($order_data);
            if ($order_info['mc_id']) {
                $mc_update_data = array(
                    'id' => $order_info['mc_id'],
                    'status' => 1,
                    'used_time' => '',
                );
                Db::name('member_coupons')->update($mc_update_data);
            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //完成收货
    public function finishOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        Db::startTrans();
        try {
            finishOrder($order_info);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //获取退款原因
    public function tuiReason()
    {
        $data_list = Db::name('refund_reason')
            ->where([
                'is_del' => 0,
                'status' => 1
            ])->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //订单退款 status 1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
    public function tuiOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        //2 直接退款 3,4,5需要寄回退款 1,6无法退款 todo 上线进行关闭
//        if ($order_info['status']==1||$order_info['status']==6){
//            msg(-1, '当前订单不可退款', '');
//        }
        Db::startTrans();
        try {
            $order_after = array(
                'tui_no' => 'cp' . GetOrderSN(2),
                'order_no' => $order_info['order_no'],
                'order_id' => $order_info['id'],
                'status' => 1,
                'create_time' => time(),
                'tui_reason' => $data['tui_reason'],
                'order_pay_money' => $order_info['pay_money'],
                'member_id' => $order_info['member_id'],
                'is_fa' => 1,
                'order_status' => $order_info['status']
            );
            if ($data['imgs']) {
                $order_after['imgs'] = implode(',', $data['imgs']);
            }
            if ($order_info['status'] == 2) {
                $order_after['is_fa'] = 0;
            }
            Db::name('order_after')->insertGetId($order_after);
            $update_date = array(
                'id' => $data['id'],
                'status' => 6,
                'tui_before' => $order_info['status']
            );
            Db::name('order')->update($update_date);
            Db::commit();
            msg(0, '申请完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //退款详情
    public function orderTuiDetail()
    {
        $data = $this->request->param();
        $where[] = ['order_id', '=', $data['id']];
        $order_info = Db::name('order')
            ->where('id', '=', $data['id'])
            ->find();
        $order_after = Db::name('order_after')
            ->order('create_time desc')
            ->where($where)
            ->find();
        $goods_info = Db::name('order_goods')->where([
            'order_id' => $data['id']
        ])->select();
        $order_info['order_after'] = $order_after;
        $order_info['goods_info'] = $goods_info;
        msg(0, '查询完成', $order_info);
    }

    //退款发货
    public function tuiSendOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order_after')
            ->where('id', '=', $data['order_after_id'])
            ->find();
        if (!$order_info) {
            msg(-2, '售后订单不存在', '');
        }
        if ($order_info['status'] != 2) {
            msg(-1, '当前售后不可退货', '');
        }
        $update = array(
            'id' => $data['order_after_id'],
            'express' => $data['express'],
            'express_no' => $data['express_no'],
            'is_send' => 1,
            'send_time' => time(),
            'status' => 4
        );
        Db::startTrans();
        try {
            Db::name('order_after')->update($update);
            Db::commit();
            msg(0, '发货完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //判断是否新人可领取优惠券
    public function isXinPeople()
    {
        //新人优惠券 为id 1
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        $coupon_info = Db::name('coupons')->find(1);
        if ($member_coupons) {
            msg(-1, '已领取', '');
        }
        msg(0, '查询成功', $coupon_info);
    }

    //获取新人优惠券
    public function getXinCoupons()
    {
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        if ($member_coupons) {
            msg(-1, '已领取新人优惠券', '');
        }
        $coupon_info = Db::name('coupons')->find(1);
        if (!$coupon_info) {
            msg(-1, '新人优惠券不存在', '');
        }
        Db::startTrans();
        try {
            $result_id = getCoupons($this->memberId, $coupon_info);
            Db::commit();
            msg(0, '领取成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //领取优惠卷
    public function getCoupons()
    {
        $data = $this->request->param();
        $coupon_info = Db::name('coupons')->where([
            'id' => $data['coupons_id'],
        ])->find();
        if (!$coupon_info) {
            msg(-1, '优惠券不存在', '');
        }
        Db::startTrans();
        try {
            //兑换优惠券
            $result_id = getCoupons($this->memberId, $coupon_info, 5);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //可领取优惠卷列表
    public function couponsList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['cate_id', '=', 2];
        $data_list = Db::name('coupons')->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
//                $is_get = Db::name('member_coupons')->where([
//                    'member_id' => $this->memberId,
//                    'coupon_id' => $item['id'],
//                    'is_del' => 0
//                ])->find();
                if ($item['effect_type'] == 1) {
                    $item['effect_end'] = date('Y-m-d H:i:s', $item['effect_end']);
                }
                $is_get = hasReceivedCouponRecently($this->memberId, $item['id']);
                if ($is_get) {
                    $item['is_get'] = 1;
                } else {
                    $item['is_get'] = 0;
                }

                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //通过年月显示每页 签到列表
    public function signList()
    {
        $data = $this->request->param();
        //获取年 获取月
        $year = $data['year'] ? $data['year'] : date('Y', time());
        $month = $data['month'] ? $data['month'] : date('m', time());
        $fraction_num = config('site.qd_get_coupons1') ? config('site.qd_get_coupons1') : 15;
        $result = array();
        $sign_count = 0;
        $dateList = getMonthTimestamps($year, $month);
        foreach ($dateList as $k => $v) {
            $result[$k]['time'] = $v;
            $result[$k]['date'] = date('Y-m-d', $v);
            $result[$k]['date2'] = date('m.d', $v);
            $result[$k]['date3'] = date('j', $v);
            $result[$k]['weekday'] = date('w', $v);
            switch ($result[$k]['weekday']) {
                case 0:
                    $weekday_cn = "日";
                    break;
                case 1:
                    $weekday_cn = "一";
                    break;
                case 2:
                    $weekday_cn = "二";
                    break;
                case 3:
                    $weekday_cn = "三";
                    break;
                case 4:
                    $weekday_cn = "四";
                    break;
                case 5:
                    $weekday_cn = "五";
                    break;
                case 6:
                    $weekday_cn = "六";
                    break;
            }
            $result[$k]['weekday'] = $weekday_cn;
            $result[$k]['fraction_num'] = $fraction_num;
            $sign_info = Db::name('member_coupon1')->where([
                ['member_id', '=', $this->memberId],
                ['sign_time', '=', date('Y-m-d', $v)],
                ['type', '=', 1]
            ])->find();
            if ($sign_info) {
                $result[$k]['is_sign'] = 1;
                $sign_count++;
            } else {
                $now_day = date('Y-m-d', time());
                if ($now_day > $result[$k]['date']) {
                    $result[$k]['is_sign'] = -1;
                } else {
                    $result[$k]['is_sign'] = 0;
                }
            }
        }
        $return['date_list'] = $result;
        $return['sign_count'] = $sign_count;

        msg(0, '查询成功', $return);
    }

    //判断今天是否签到
    public function isSign()
    {
        $sign_info = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['sign_time', '=', date('Y-m-d', time())],
            ['type', '=', 1]])->count();
        msg(0, '查询完成', $sign_info);
    }

    //会员签到
    public function sign()
    {
        //当天是否签到
        $timeRang = getTimestamp(0);
        $sign_time = date('Y-m-d', time());
        $sign_info = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['sign_time', '=', $sign_time],
            ['type', '=', 1]
        ])->find();
        if ($sign_info) {
            msg(-1, '今日已签到', '');
        }
        Db::startTrans();
        try {
            $fraction_num = config('site.qd_get_coupons1') ? config('site.qd_get_coupons1') : 15;
            addGWCoupons($this->memberId, $fraction_num, '', '', 1, '签到');
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    // 臻品区、健康区、拼团区直接购买、砍价区直接购买
    public function createOrder()
    {
        $data = $this->request->param();
        //判断库存 是否可买
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => $goods_info['goods_area'], //订单类型 1拼团区 2臻品区 3砍价区 4健康区
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark']
        );
        //1拼团区 2臻品区 3砍价区 4健康区
        if ($goods_info['goods_area'] == 1) {
            $insert_data['pin_type'] = 2;
        }
        if ($goods_info['goods_area'] == 3) {
            $insert_data['can_type'] = 2;
        }
        if ($data['delive_type'] == 1) {
            $insert_data['province'] = $data['province'];
            $insert_data['city'] = $data['city'];
            $insert_data['area'] = $data['area'];
            $insert_data['address'] = $data['address'];
            $insert_data['supply_id'] = $goods_info['supply_id'];
        }
        if ($data['delive_type'] == 2) {
            $insert_data['shop_id'] = $data['shop_id'];
        }
        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        //todo 优惠卷金额 购物卷金额
//        if ($data['mc_id'] && $data['coupons1']) {
//            msg(-1, '优惠卷和购物卷不能同时使用', '');
//        }
        if ($data['coupons1'] && !$data['mc_id']) {
            $insert_data['order_money'] = round($insert_data['origin_price'] - $data['coupons1'], 2);
            $insert_data['shop_coupon'] = $data['coupons1'];
            addGWCoupons($this->memberId, -$data['coupons1'], '', '', 3, '消费');
        }
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($insert_data['order_money'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['order_money'] = round($insert_data['origin_price'] - $member_coupons['value'], 2);
        }
        $insert_data['pay_money'] = $insert_data['order_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //订单发起支付
    public function orderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    // 臻品区、健康区、拼团区直接购买、砍价区直接购买 订单回调
    public function orderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            //todo 支付成功测试
//            orderPaySuccess($order_data);
//            Db::commit();
//            msg(0, "支付成功！", $order_data);

            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    orderPaySuccess($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function ccorderPayBack2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            upMemberVip2($order_data);
            Db::commit();
            msg(0, "支付成功！", $order_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    public function orderDetail()
    {
        $data = $this->request->param();
        $return_detail = Db::name('order')->where('order_no', '=', $data['id'])->find();
        Db::startTrans();
        try {
            if (!$return_detail) {
                msg(-1, '订单不存在', '');
            }
            $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
            if ($return_detail['pay_time']) {
                $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
            }
            if ($return_detail['tui_time']) {
                $return_detail['tui_time'] = date('Y-m-d H:i:s', $return_detail['tui_time']);
            }
            if ($return_detail['send_time']) {
                $return_detail['send_time'] = date('Y-m-d H:i:s', $return_detail['send_time']);
            }
            $order_goods = Db::name('order_goods')
                ->where('order_id', '=', $return_detail['id'])
                ->select();
            $return_detail['order_goods'] = $order_goods;
            //自提订单生成二维码取货码
//            if ($return_detail['pay_status'] == 1 && $return_detail['delive_type'] == 2) {
            if ($return_detail['delive_type'] == 2) {
                if (!$return_detail['write_code']) {
                    $write_code_digits = rand(1000, 9999);
                    //todo  /pages/order/orderDetails/orderDetails?id=${value.order_no}
                    // pages/order/orderDetails/orderDetails
                    $qr_code = qrcode($return_detail['order_no'], 'pages/order/orderDetails/orderDetails');
                    // $qr_code = qrcode($return_detail['id'], 'pages/shop/TionData/TionData?id='.$return_detail['order_no'].'&state=${2}');
                    $update_order = array(
                        'id' => $return_detail['id'],
                        'write_code' => $qr_code,
                        'write_code_digits' => $write_code_digits
                    );
                    Db::name('order')->update($update_order);
                    $return_detail['write_code'] = $qr_code;
                    $return_detail['write_code_digits'] = $write_code_digits;
                }
            }
            $shop_info = Db::name('shop')->find($return_detail['shop_id']);
            $return_detail['shop_info'] = $shop_info;
            Db::commit();
            msg(0, '查询成功', $return_detail);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //todo 获取拼团卷数量 判断是否
    //发起拼团
    public function creatPTOrder()
    {
        $data = $this->request->param();
        //todo 增加身份老人才能发起拼团
        if ($this->memberInfo['is_clock'] == 0) {
            msg(-2, '新人不能发起拼团', '');
        }
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.pin_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        //order_type 订单类型 1拼团区 2臻品区 3砍价区 4健康区
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 1,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'pin_sort' => 1,
            'remark' => $data['remark']
        );
        //判断自提还是邮寄 配送类型 1快递订单 2自提订单
        if ($data['delive_type'] == 1) {
            $insert_data['province'] = $data['province'];
            $insert_data['city'] = $data['city'];
            $insert_data['area'] = $data['area'];
            $insert_data['address'] = $data['address'];
            $insert_data['supply_id'] = $goods_info['supply_id'];
        }
        if ($data['delive_type'] == 2) {
            $insert_data['shop_id'] = $data['shop_id'];
        }
        $insert_data['origin_price'] = round($goods_info['pin_price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];

        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['pin_price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['pin_price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //拼团发起支付
    public function PtOrderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //支付回调
    public function PtOrderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();

//            PtOrderPaySuccess($order_data);
//            Db::commit();
//            msg(0, "支付成功！", $order_data);

            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    PtOrderPaySuccess($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取拼团卷数量
    public function getPtCoupons()
    {
        msg(0, '查询成功', $this->memberInfo['coupon2']);
    }

    //拼团卷支付
    public function PtCouponsPay()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')
            ->where('order_no', '=', $data['order_no'])
            ->find();
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        if ($order_info['order_money'] > $this->memberInfo['coupon2']) {
            msg(-2, '拼团卷不足', '');
        }
        if ($order_info['status'] != 1) {
            msg(-3, '订单状态错误', '');
        }
        PtOrderPaySuccess($order_info, 2);
        addPTCoupons($order_info['member_id'], -$order_info['order_money'], $order_info['id'], 2, '拼团使用');
        $return_order = Db::name('order')->find($order_info['id']);
        msg(0, '支付完成', $return_order);
    }

    //todo 判断是否新人
    public function isNewUser()
    {
        $data = $this->request->param();
    }

    //获取发起拼团订单详情
    public function getPtOrderDetail()
    {
        $data = $this->request->param();
//        $group_activities_id = $data['group_activities_id'];
        $order_info = Db::name('order')->where([
            'order_no' => $data['order_no']
//            'activity_id' => $group_activities_id,
//            'member_id' => $this->memberId
        ])->find();
        $order_goods = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->find();
        $where = array(
            'g.id' => $order_goods['goods_id'],
//            'g.is_del' => 0,
//            'g.status' => 1,
            'gav.suk' => $order_goods['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
            ->where($where)
            ->find();
        $group_activities = Db::name('group_activities')->find($order_info['activity_id']);
        $group_participants = Db::name('group_participants')->alias('gr')
            ->field('gr.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=gr.member_id')
            ->order('gr.create_time')->where([
                'gr.group_active_id' => $order_info['activity_id']
            ])->select();
        $c_num = $group_activities['group_num'] - count($group_participants);
        for ($i = $c_num; $i > 0; $i--) {
            $group_participants[] = [];
        }
        $return_data['order_info'] = $order_info;
        $return_data['goods_info'] = $goods_info;
        $group_activities['now_member_id'] = $this->memberId;
        $return_data['group_activities'] = $group_activities;
        $return_data['group_participants'] = $group_participants;
        msg(0, '查询完成', $return_data);
    }

    //获取分享拼团详情
    public function getPtOrderDetail2()
    {
        $data = $this->request->param();
        $group_activities_id = $data['group_activities_id'];
        $group_activities = Db::name('group_activities')->find($group_activities_id);

        $order_info = Db::name('order')->where([
            'activity_id' => $group_activities_id,
            'member_id' => $group_activities['member_id']
        ])->find();
        $order_goods = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->find();
        $where = array(
            'g.id' => $order_goods['goods_id'],
            'gav.suk' => $order_goods['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
            ->where($where)
            ->find();

        $group_participants = Db::name('group_participants')->alias('gr')
            ->field('gr.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=gr.member_id')
            ->order('gr.create_time')->where([
                'gr.group_active_id' => $group_activities_id
            ])->select();
        $c_num = $group_activities['group_num'] - count($group_participants);
        for ($i = $c_num; $i > 0; $i--) {
            $group_participants[] = [];
        }
        $return_data['order_info'] = $order_info;
        $return_data['goods_info'] = $goods_info;
        $return_data['group_activities'] = $group_activities;
        $return_data['group_participants'] = $group_participants;
        msg(0, '查询完成', $return_data);
    }


    //判断是否可以参加拼团
    public function isCanPin()
    {
        $data = $this->request->param();
        isCanPin($data['group_activities_id'], $this->memberId);
        msg(0, '查询成功', '');
    }

    //创建参加拼团订单
    public function addPt()
    {
        $data = $this->request->param();
        isCanPin($data['group_activities_id'], $this->memberId);
        //获取活动
        $pin_order = Db::name('order')->where([
            'activity_id' => $data['group_activities_id'],
            'pin_sort' => 1,
            'order_type' => 1
        ])->find();
        //获取拼团的商品
        $pin_order_goods = Db::name('order_goods')->where(['order_id' => $pin_order['id']])->find();
        $where = array(
            'g.id' => $pin_order_goods['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.pin_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9拼团中
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 1,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'activity_id' => $data['group_activities_id'],
            'remark' => $data['remark']
        );
        if ($data['delive_type'] == 1) {
            $insert_data['province'] = $data['province'];
            $insert_data['city'] = $data['city'];
            $insert_data['area'] = $data['area'];
            $insert_data['address'] = $data['address'];
            $insert_data['supply_id'] = $goods_info['supply_id'];
        }
        if ($data['delive_type'] == 2) {
            $insert_data['shop_id'] = $data['shop_id'];
        }
        $insert_data['origin_price'] = round($goods_info['pin_price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $pin_order_goods['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['pin_price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['pin_price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //参加拼团发起支付
    public function PtOrderPay2()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
//        isCanPin($order_data['activity_id'], $this->memberId);
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
              $result = $app->order->unify([
            'body' => '拼团购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") .'/pdOrderNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);

        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //创建参加拼团订单 支付回调
    public function PtOrderPayBack2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            //todo 测试
//            PtOrderPaySuccess2($order_data);
//            die();
//            Db::commit();
//            msg(0, "支付成功！", $order_data);

                $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    PtOrderPaySuccess2($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //我的拼团
    public function myPtList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type']; //0全部 1进行中 2已完成
        $where[] = ['o.pin_type', '=', 1];
        $where[] = ['o.order_type', '=', 1];
        $where[] = ['o.status', 'in', [2, 3, 4, 8, 9]];
        $where[] = ['o.member_id', '=', $this->memberId];
        if ($type == 0) {
            $where[] = ['ga.status', 'in', [1, 2]];
        }
        if ($type == 1) {
            $where[] = ['ga.status', '=', 1];
        }
        if ($type == 2) {
            $where[] = ['ga.status', '=', 2];
        }
        $order_list = Db::name('order')->alias('o')
            ->join('group_activities ga', 'o.activity_id=ga.id')
            ->field('o.*,ga.group_num,ga.now_num,ga.status as ga_status')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $order_goods = Db::name('order_goods')->where([
                    'order_id' => $item['id']
                ])->find();
                $goods_info_where = array(
                    'g.id' => $order_goods['goods_id'],
//            'g.is_del' => 0,
//            'g.status' => 1,
                    'gav.suk' => $order_goods['suk']
                );
                $goods_info = Db::name('goods')->alias('g')
                    ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                    ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
                    ->where($goods_info_where)
                    ->find();
                $item['goods_info'] = $goods_info;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);

                $item['group_participants'] = Db::name('group_participants')->alias('gr')
                    ->field('gr.*,m.nickname,m.avatarUrl')
                    ->join('member m', 'm.id=gr.member_id')
                    ->order('gr.create_time')->where([
                        'gr.group_active_id' => $item['activity_id']
                    ])->select();
                $group_activities = Db::name('group_activities')->find($item['activity_id']);
                if ($group_activities['member_id'] == $this->memberId) {
                    $item['is_gan'] = 1;
                } else {
                    $item['is_gan'] = 0;
                }

                return $item;
            });
        msg(0, '查询完成', $order_list);
    }


    //获取用户信息顶部卷
    public function myTopCoupons()
    {
        //coupons
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $coupons_count = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->count();
        $return_data['a'] = $this->memberInfo['coupon1'];
        $return_data['b'] = $this->memberInfo['coupon2'];
        $return_data['c'] = $coupons_count;
        msg(0, '查询成功', $return_data);
    }

    //我的优惠卷列表
    public function getMemberCouponsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('member_coupons')->where([
            'status' => 1,
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->order('create_time desc')
            ->paginate($length, false, ['page' => $page])->each(function ($item) {
                //start_time    end_time
                $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
                $item['back_img_url'] = config('site.coupons_bg');
                $item['open'] = 0;
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //判断用户是否可发起砍价
    public function isCreateBargain()
    {
        //判断是否新人 老人才能砍价
        //一个品只能发起一次砍价(成功、进行中) todo
        $data = $this->request->param();
        $goods = $data['goods_id'];
        if ($this->memberInfo['level_id'] < 2) {
            msg(-1, "当前等级不能砍价", 1);
        }
        msg(0, "查询成功", 1);
    }

    //发起砍价
    public function createBargain()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            //suk goods_id
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['suk']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.min_price')
                ->where($where)
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在,或下架', '');
            }
            $insert_data = array(
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'member_id' => $this->memberId,
                'price' => $goods_info['price'],
                'current_price' => $goods_info['price'],
                'target_price' => $goods_info['min_price'],
                'bargain_times' => 0,
                'max_bargain_times' => $goods_info['bargain_count'],
                'create_time' => time(),
                'end_time' => time() + ($goods_info['bargain_time'] * 60),
            );
            $bargain_activity_id = Db::name('bargain_activity')->insertGetId($insert_data);
            $insert_data['id'] = $bargain_activity_id;
            //1随机金额2固定金额
            if ($goods_info['sj_kan'] == 1) {
                $bargain_money_list = bargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
            } else {
                $bargain_money_list = averageBargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
            }
            foreach ($bargain_money_list as $k => $v) {
                $bargain_money_insert = array(
                    'cut_amount' => $v['cut_amount'],
                    'current_price' => $v['current_price'],
                    'ba_id' => $bargain_activity_id,
                    'sort' => $k + 1
                );
                Db::name('bargain_money')->insertGetId($bargain_money_insert);
            }
            Db::commit();
            msg(0, "创建成功", $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //是否可砍价
    public function isCanBargain()
    {
        $data = $this->request->param();
        isCanBargain($data['bargain_activity_id'], $this->memberId);
        msg(0, "查询成功", 1);
    }

    //参与砍价
    public function joinBargain()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            //todo 测试打开
            isCanBargain($data['bargain_activity_id'], $this->memberId);
            $bargain_record_data = bargainJoin($data['bargain_activity_id'], $this->memberId);
            bargainFinish($data['bargain_activity_id']);
            Db::commit();
            msg(0, "砍价成功", $bargain_record_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //砍价记录
    public function getBargainRecord()
    {
        $data = $this->request->param();
        $group_participants = Db::name('bargain_record')->alias('br')
            ->field('br.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=br.member_id')
            ->order('br.create_time')->where([
                'br.activity_id' => $data['bargain_activity_id']
            ])->select();
        foreach ($group_participants as $k => $v) {
            $group_participants[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        msg(0, '查询完成', $group_participants, count($group_participants));
    }

    //我的砍价列表
    public function myBargainList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type']; //0全部 1进行中 2已完成
        $where[] = ['ba.member_id', '=', $this->memberId];
        if ($type == 0) {
            $where[] = ['ba.bargain_status', 'in', [1, 2, 3]];
        } else {
            $where[] = ['ba.bargain_status', '=', $type];
        }
        $bargain_list = Db::name('bargain_activity')->alias('ba')
            ->join('goods g', 'g.id=ba.goods_id')
            ->field('ba.*,g.name as goods_name,g.first_img')
            ->order('ba.create_time desc')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $bargain_record = Db::name('bargain_record')->alias('br')
                    ->field('br.*,m.nickname,m.avatarUrl')
                    ->join('member m', 'm.id=br.member_id')
                    ->order('br.create_time')->where([
                        'br.activity_id' => $item['id']
                    ])->select();
                $item['count_num'] = count($bargain_record);
                $item['bargain_record'] = $bargain_record;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $bargain_list);
    }

    //砍价创建订单
    public function createBargainOrder()
    {
        $data = $this->request->param();
        $data['num'] = 1;
        $bargain_activity = Db::name('bargain_activity')->find($data['bargain_activity_id']);
        //todo 上线放开
//        if ($bargain_activity||$bargain_activity['status']!=1){
//            msg(-1, '砍价未完成', '');
//        }
        //创建砍价订单
        $where = array(
            'g.id' => $bargain_activity['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $bargain_activity['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 10,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货  9拼团中 10砍价发起
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => $goods_info['goods_area'], //订单类型 1拼团区 2臻品区 3砍价区 4健康区
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark'],
            'can_type' => 1,
            'bargain_activity_id' => $bargain_activity['id'],
            'cut_money' => $bargain_activity['price'] - $bargain_activity['current_price']
        );
        if ($data['delive_type'] == 1) {
            $insert_data['province'] = $data['province'];
            $insert_data['city'] = $data['city'];
            $insert_data['area'] = $data['area'];
            $insert_data['address'] = $data['address'];
            $insert_data['supply_id'] = $goods_info['supply_id'];
        }
        if ($data['delive_type'] == 2) {
            $insert_data['shop_id'] = $data['shop_id'];
        }
        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $bargain_activity['current_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId($insert_data);
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $bargain_activity['goods_id'],
                'suk' => $bargain_activity['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //砍价发起支付
    public function bargainOrderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //砍价支付回调
    public function bargainOrderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 10) {
                    bargainOrderSuccess2($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断是否可以申请小店
    public function isCanApplyShop()
    {

        // -1 为不能申请
        $shop_info = Db::name('shop')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if ($shop_info && $shop_info['status'] == 0) {
            msg(1, "审核中", '');
        }
        if ($shop_info && $shop_info['status'] == 3) {
            msg(0, "可申请", '');
        }
        if ($this->memberInfo['level_id'] >= 3) {
            msg(0, "可申请", '');
        }
        $result = isShop($this->memberId);
        if ($result == -1) {
            msg(-1, "不可以申请", '');
        } else {
            msg(0, "可申请", '');
        }
    }

    //申请小店
    public function applyShop()
    {
        $data = $this->request->param();
        $business_data = Db::name('shop')
            ->where('is_del', 0)
            ->where(['member_id' => $this->memberId])
            ->find();
        if ($business_data && $business_data['status'] != 3) {    //存在且不是审核失败
            msg(-1, '您已申请,请勿重复提交', '');
        }
        $create_time = time();
        $insert_data = array(
            'member_id' => $this->memberId,
//            'province' => $data['province'],
//            'city' => $data['city'],
//            'area' => $data['area'],
            'address' => $data['address'],
            'shop_name' => $data['shop_name'],
            'people' => $data['people'],
            'phone' => $data['phone'],
            'create_time' => $create_time,
            'latitude' => $data['latitude'],
            'longitude' => $data['longitude'],
        );
        $time = explode('-', $data['operate_time']);
        $insert_data['start_time'] = $time[0];
        $insert_data['end_time'] = $time[1];
        if ($data['remark']) {
            $insert_data['remark'] = $data['remark'];
        }
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $address_info = $data_list['data']['address_component'];
            $insert_data['province'] = $address_info['province'];
            $insert_data['city'] = $address_info['city'];
            $insert_data['area'] = $address_info['district'];
        }
        Db::startTrans();
        try {
            //重新提交
            if ($business_data && $business_data['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $business2_id = Db::name('shop')
                    ->where([
                        'is_del' => 0,
                        'member_id' => $this->memberId
                    ])->update($insert_data);
                Db::name('shop_img')->where('shop_id', $business_data['id'])->delete();
                $business_id = $business_data['id'];
            } else {
                $business_id = Db::name('shop')->insertGetId($insert_data);
            }
            foreach ($data['operate_img'] as $k => $v) {
                $insert_img_data = array(
                    'shop_id' => $business_id,
                    'sort' => $k + 1,
                    'img' => $v
                );
                Db::name('shop_img')->insertGetId($insert_img_data);
            }
            Db::commit();
            msg(0, '查询成功', $business_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    /**
     * 获取成为商家审核状态
     */
    public function getShopStatus()
    {
        $data = Db::name('shop')->where(['member_id' => $this->memberId, 'is_del' => 0])->find();
        if ($data) {
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }




    //推荐拼团
    //todo 订单取消时 回复优惠卷 购物卷
    //todo  自己拼团不能参加 不能重复参加拼团
    //todo 后台小店核销记录 小店自提不影响库存 库存也有整体库存 整体销量进行同步
    //todo 后台充值 拼团卷 购物卷 我的 商家入户 审核 商家列表
    // 根据不同身份等级返现 看群消息AA 小店核销返现 小店后台核销记录 拼团推荐
    // 定时任务 拼团时间到期 拼团订单更新（不管是否拼团成功） 拼团成功的状态进行设置
    // 定时任务 砍价最低为0时生成订单

    public function getShopList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city = $data['city'];
//        $range = input('range/d', 50000);
        $where[] = ['province|city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];

//        $latRange = $range / 111320;
//        $lngRange = $range / (111320 * cos(deg2rad($latitude)));
//        $minLat = $latitude - $latRange;
//        $maxLat = $latitude + $latRange;
//        $minLng = $longitude - $lngRange;
//        $maxLng = $longitude + $lngRange;
//        $where[] = ['latitude', 'between', [$minLat, $maxLat]];
//        $where[] = ['longitude', 'between', [$minLng, $maxLng]];

        $result = [];
        $data_list = Db::name('shop')
            ->where($where)
            ->page($page, $length)
            ->select();
        if (count($data_list) == 0) {
            msg(0, '查询成功', '');
        }
        if (!$latitude || !$longitude) {
            msg(0, '查询成功', '');
        }
        foreach ($data_list as $k => $v) {
            $distance = distanceHaversine($latitude, $longitude, $v['latitude'], $v['longitude']) * 1000;
//            if ($distance <= $range) {
            $v['distance'] = round($distance);
            $result[] = $v;
//            }
        }
        usort($result, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        foreach ($result as $k => $v) {
            if ($k == 0) {
                $result[$k]['is_select'] = 2;
                $result[$k]['is_distance'] = 1;
            } else {
                $result[$k]['is_select'] = 1;
                $result[$k]['is_distance'] = 2;
            }
        }
        //todo 测试经纬度距离是否正确
        msg(0, '查询成功', $result, count($result));
    }

    //获取最近商店
    public function getShopDistance()
    {
        $data = $this->request->param();
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city = $data['city'];
        $where[] = ['province|city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $data_list = Db::name('shop')
            ->where($where)
            ->select();
        if (count($data_list) == 0) {
            msg(0, '查询成功', '');
        }
        if (!$latitude || !$longitude) {
            msg(0, '查询成功', '');
        }
        foreach ($data_list as $k => $v) {
            $distance = distanceHaversine($latitude, $longitude, $v['latitude'], $v['longitude']) * 1000;
            $v['distance'] = round($distance);
            $result[] = $v;
        }
        usort($result, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        msg(0, '查询成功', $result[0]);
    }

    //账户中心四个
    public function accountCenter()
    {
        //可提现
        $a = $this->memberInfo['money'];
        $b = Db::name('reward')->where([
            'member_id' => $this->memberId,
            'status' => 0
        ])->sum('money');
        $c = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 6],
            ['is_kuan', '=', 0],
        ])->sum('money');
        $d = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 6],
            ['is_kuan', '=', 1],
        ])->sum('money');
        $return['a'] = $a;
        $return['b'] = $b;
        $return['c'] = $c;
        $return['d'] = $d;
        msg(0, '查询成功', $return);
    }

    //提现
    public function tixian()
    {
        $data = $this->request->param();
        if ($data['money'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['money'] > $this->memberInfo['money']) {
            msg(-1, '提现金额不能大于余额', '');
        }
        if ($data['money'] < $this->memberInfo['min_tx']) {
            msg(-2, '最低提现金额' . $this->memberInfo['min_tx'], '');
        }
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'money' => $data['money'],
                'type' => 6,
                'tixian_type' => $data['tixian_type'], //1银行 2支付宝 3微信
                'tixian_account' => $data['tixian_account'], //提现账号
                'tixian_name' => $data['tixian_name'],//提现人姓名
                'tixian_bank' => $data['tixian_bank'],//提现银行名（银行提现使用）
                'desc' => '余额提现',
                'status' => 0,//'0未完成 待审核 1已完成 审核完成 提现使用',
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_data['shou_money'] = round($data['money'] * (0.07), 2);
            $insert_data['shou_money'] = 0;
            $insert_data['true_money'] = $data['money'] - $insert_data['shou_money'];
            $insert_id = Db::name('member_finance')->insertGetId($insert_data);
            Db::name('member')
                ->where('id', '=', $this->memberId)
                ->setDec('money', $data['money']);
            Db::commit();
            msg(0, '申请成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //提现记录
    public function tixianList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['type', '=', 6];
        $data_list = Db::name('member_finance')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $data_list[$k]['status_time'] = date('Y-m-d H:i:s', $v['status_time']);
            $data_list[$k]['kuan_time'] = date('Y-m-d H:i:s', $v['kuan_time']);
        }
        msg(0, '查询成功', $data_list);
    }
    //分销订单列表
    //我的下线
    //我的团队
    public function myTeam()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $cort_type = $data['cort_type'];
        if ($cort_type == 1) {
            $sort = 'create_time desc';
        } else {
            $sort = 'create_time';
        }
        $where[] = ['invite_id', '=', $this->memberId];
        $data_list = Db::name('member')->where($where)
            ->order($sort)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['money'] = Db::name('reward')->where([
                    ['junior_member_id', '=', $item['id']],
                    ['member_id', '=', $this->memberId],
                    ['status', '=', 1],
                ])->sum('money');
                $item['order_num'] = Db::name('reward')->where([
                    ['junior_member_id', '=', $item['id']],
                    ['member_id', '=', $this->memberId],
                    ['status', '=', 1],
                ])->count();
                $team_num = Db::name('member')->where('invite_id', '=', $item['id'])->count();
                $item['team_num'] = $team_num;
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    public function PtCGw()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if ($data['coupon2'] <= 0) {
                msg(-1, '请输入正确数量', '');
            }
            if ($data['coupon2'] > $this->memberInfo['coupon2']) {
                msg(-2, '请输入正确数量', '');
            }
            addPTCoupons($this->memberId, -$data['coupon2'], '', 3, '转换购物卷');
            addGWCoupons($this->memberId, $data['coupon2'], '', '', 4, '拼团卷兑换');
            Db::commit();
            msg(0, '兑换成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //拼团卷明细
    public function PTCouponsHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //cate 0收入 1支出
        $type = $data['cate'];
        $where[] = ['member_id', '=', $this->memberId];
        if ($type == 1) {
            $where[] = ['num', '>', 0];
        } elseif ($type == 2) {
            $where[] = ['num', '<', 0];
        }
        $data_list = Db::name('member_coupon2')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //分销订单
    public function shouDetailList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $order_list = Db::name('reward')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['member_info'] = Db::name('member')->field('nickname,avatarUrl')->find($item['junior_member_id']);
                $item['goods_info'] = Db::name('goods')->field('name,first_img')->find($item['goods_id']);
                $price = Db::name('goods_attr_value')->where([
                    'goods_id' => $item['goods_id']
                ])->find();
                $item['goods_info']['price'] = $price['price'];
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //todo 后台可调节上级 购物卷兑换 快递显示
    // 用户分红 分销订单 我的成就 只显示一级 用户提现 提现记录 分销逻辑修改 拼团卷兑换购物卷
    // 商家营业时间入驻 商家接口时间设置 后台快递代码设置 快递接口
    // 砍价成功 拼团成功 拼团卷记录 物流  购物299 成会员 拼团返卷 设置新人  同步商品库存销量  AB返钱  直推奖励  申请小店成功小店
    // 商家提现后台管理 订单管理设置  账单信息 首页 订单后台 购物返购物卷  小程序细节 后台调整 库存销量同步 后台退款

    /**
     * Desc 创建订单
     * Create on 2024/10/22 9:50
     * Create by wangyafang
     */
    public function create()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->post();

        $param['wechat_id'] = User::getWechatId($this->auth->id);

        $create_data = array(
            'wechat_id' => $param['wechat_id'],
            'order_no' => wddj_create_order(),
            'price' => $param['price'],
            'order_id' => $param['order_id'],
        );
        $this->model->allowField(true)->save($create_data);

        try {
            $openid = wddj_get_openid($param['wechat_id']);
            $conf = Wxapp::unify('追加费用', $create_data['order_no'], $create_data['price'], $openid, request()->domain() . '/api/wddj/user/order_additional_price_log/order_additional_notify');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }


        $this->success('微信预支付调用成功', array(
            'id' => $this->model->id,
            'conf' => $conf,
        ));
    }


}
